package com.mac.hosp_pre.user.api;

import cn.hutool.core.util.CharsetUtil;
import com.mac.hosp_pre.except.ServiceException;
import com.mac.hosp_pre.reply.R;
import com.mac.hosp_pre.user.config.WechatProperties;
import com.mac.hosp_pre.user.model.resp.UserRespDto;
import com.mac.hosp_pre.user.service.UserInfoService;
import com.mac.hosp_pre.util.JwtUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.apache.commons.codec.Charsets;
import org.apache.commons.lang3.CharSet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

@Tag(name = "微信操作接口")
@Slf4j
@Controller
@RequestMapping("/api/user/wx")
public class WeixinApiController {
    @Autowired
    private UserInfoService userInfoService;


    @Autowired
    private WxMpService wxMpService;

    @Autowired
    private WechatProperties wechatProperties;


    //授权跳转
    @Operation(summary = "授权跳转")
    @GetMapping("/authorize")
    public String authorize(@RequestParam("returnUrl") String returnUrl,
                            HttpServletRequest request) {
        String url = wxMpService.getOAuth2Service().buildAuthorizationUrl(wechatProperties.getUserInfoUrl(),
                WxConsts.OAuth2Scope.SNSAPI_USERINFO,
                URLEncoder.encode(returnUrl));

        return "redirect:"+url;
    }

    @Operation(summary = "获取用户信息")
    @GetMapping("/userInfo")
    public String userInfo(@RequestParam("code") String code,
                           @RequestParam("state") String returnUrl) {
        try {
            //拿着code请求
            WxOAuth2AccessToken accessToken = wxMpService.getOAuth2Service().getAccessToken(code);
            //获取openid
            String openId = accessToken.getOpenId();

            //获取微信信息
            WxOAuth2UserInfo auth2UserInfo = wxMpService.getOAuth2Service().getUserInfo(accessToken, null);

            //获取微信信息添加数据库
            UserRespDto userInfo = userInfoService.getOrSaveUserInfoOpenId(auth2UserInfo,openId);
            String token = userInfo.getToken();
            if(returnUrl.indexOf("?") == -1) {
                return "redirect:"+returnUrl+"?"+JwtUtil.TOKEN_NAME+"="+token;
            } else {
                return "redirect:"+returnUrl+"&"+JwtUtil.TOKEN_NAME+"="+token;
            }

        }catch (WxErrorException e) {
            throw new ServiceException(e.getError().getErrorCode(),e.getError().getErrorMsg());
        }
    }

    //1 生成微信扫描二维码
    //返回生成二维码需要参数
    @GetMapping("getLoginParam")
    @ResponseBody
    public R genQrConnect() {
        try {
            Map<String, Object> map = new HashMap<>();
            String wxOpenRedirectUrl = URLEncoder.encode(wechatProperties.getWx_redirect_url()+"?returnUrl="+wechatProperties.getReturn_url(), CharsetUtil.UTF_8);
            map.put("redirect_uri",wxOpenRedirectUrl);
            map.put("state",System.currentTimeMillis()+"");
            return R.success(map);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
